package Cart_Servlet;

import java.io.IOException;
import java.util.ArrayList;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import Cart_Function.Cart_Function;
import Cart_Function.SetOrder_Function;
import Cart_Utils.Cart;

/**
 * Servlet implementation class SetOrder_Servlet
 */
@WebServlet("/SetOrder_Servlet")
public class SetOrder_Servlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public SetOrder_Servlet() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		response.setContentType("text/html;charset=utf-8");
		String user = (String) request.getSession().getAttribute("UserName");
		ArrayList<Cart> carts = (ArrayList<Cart>) request.getSession().getAttribute("carts");
		
		new SetOrder_Function().SetOrder(carts);
		String msg ;
		if(null==request.getSession().getAttribute("order"))
			msg = "预定成功！";
		else
			msg = "已存在订单，不可更改。或联系管理员";
		request.setAttribute("msg", msg);
		
		new Cart_Function().empty(user);
		
		
		
		ArrayList<Cart> order = new SetOrder_Function().getOrder(user);
		int allTotal = 0;
		for(int i=0;i<order.size();i++){
			allTotal += Integer.parseInt(order.get(i).getTotal()); 
		}
		request.getSession().removeAttribute("carts");
		request.getSession().setAttribute("order", order);
		request.setAttribute("allTotal", allTotal);
		request.getRequestDispatcher("orderView.jsp").forward(request, response);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		doGet(request, response);
	}

}
